package com.tttrark.coursearrange.service.impl;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.tttrark.coursearrange.entity.Admin;
import com.tttrark.coursearrange.entity.Student;
import com.tttrark.coursearrange.entity.Teacher;
import org.springframework.stereotype.Service;

import java.util.Date;


@Service
public class TokenService {

    // 统一的 Token 有效期（1小时，单位：毫秒）
    private static final long TOKEN_EXPIRATION_TIME = 60 * 60 * 1000;

    /**
     * 生成学生 Token
     */
    public String generateStudentToken(Student student) {
        return generateToken(student.getId().toString(), student.getPassword());
    }

    /**
     * 生成管理员 Token
     */
    public String generateAdminToken(Admin admin) {
        return generateToken(admin.getId().toString(), admin.getPassword());
    }

    /**
     * 生成教师 Token
     */
    public String generateTeacherToken(Teacher teacher) {
        return generateToken(teacher.getId().toString(), teacher.getPassword());
    }

    /**
     * 通用 Token 生成方法
     */
    private String generateToken(String subject, String secret) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + TOKEN_EXPIRATION_TIME);

        return JWT.create()
                .withSubject(subject)
                .withIssuedAt(now)
                .withExpiresAt(expiration)
                .sign(Algorithm.HMAC256(secret));
    }
}
